<?php
namespace app\admin\controller;
use think\facade\View;

use think\facade\Db;
use think\facade\Request;
use think\facade\Session;
use think\facade\Env;
class Customer extends Common{
    public $model;
    public function initialize()
    {
        parent::initialize();
        $this->model=new \app\admin\model\Client();
    }
    //客户列表
    public function index(){
        if($this->request->isAjax()){
            [$where, $sort, $order, $offset, $limit] = $this->buildparams();
            $total = $this->model
                ->where($where)->where(['status'=>1,'issuccess'=>-1])
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)->where(['status'=>1,'issuccess'=>-1])
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select()->toArray();

            $result = ['total' => $total, 'rows' => $list];

            return json($result);


            return json($result);
            $page =input('page',1,'intval');
            $pageSize =input('limit',config('app.pageSize'),'intval');
            $list = \think\facade\Db::name('crm_customer')
                ->where(['status'=>1,'issuccess'=>-1])
                ->order('at_time desc')
                ->paginate(['list_rows'=>$pageSize,'page'=>$page])
                ->toArray();
            return json(['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1]);
        }

        $khRankList = Db::table('crm_client_rank')->select();
        $khStatusList = Db::table('crm_client_status')->select();
        $xsSourceList = Db::table('crm_source')->select();

        //查询所有管理员（去除admin）
        $adminResult = Db::name('admin')->where('group_id','<>', 1)->field('admin_id,username')->select();
        View::assign('adminResult',$adminResult);

        View::assign('khRankList',$khRankList);
        View::assign('khStatusList',$khStatusList);
        View::assign('xsSourceList',$xsSourceList);  //线索/客户来源

        return View::fetch();
    }

    //（我的客户）列表
    public function perclilist(){

        if($this->request->isPost()){
            $page =input('page',1,'intval');
            $pageSize =input('limit',config('app.pageSize'),'intval');
            $list = \think\facade\Db::name('crm_customer')
                ->where(['status'=>1,'issuccess'=>-1])
                ->where(['pr_user'=> $this->admin['username']])
                ->order('ut_time desc')
                ->paginate(['list_rows'=>$pageSize,'page'=>$page])
                ->toArray();
             // 是否有查看手机号的权限
            $userinfo = Db::name('admin')->where('username',$this->admin['username'])->find();
            if ($userinfo['isphone'] == 0) {
                foreach ($list['data'] as $key => $value) {
                    $value['phone'] = mb_substr($value['phone'], 0, 3).'****'. mb_substr($value['phone'], 7, 11);
                    $list['data'][$key] = $value;
                }
            }
            return  ['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }

        $khRankList = Db::table('crm_client_rank')->select();
        $khStatusList = Db::table('crm_client_status')->select();
        $xsSourceList = Db::table('crm_source')->select();

        View::assign('khRankList',$khRankList);
        View::assign('khStatusList',$khStatusList);
        View::assign('xsSourceList',$xsSourceList);  //线索/客户来源

        return View::fetch();
    }

     //成交客户列表
    public function successCliList(){

        if($this->request->isPost()){
            $where = [];
            $where['issuccess'] = 1;
            $where['status'] = 1;
            if($this->admin['admin_id']!=1){
                 $where['pr_user'] = $this->admin['username'];
            }
            $page =input('page',1,'intval');
            $pageSize =input('limit',config('app.pageSize'),'intval');

            $list = \think\facade\Db::name('crm_customer')
                ->where($where)
                ->order('ut_time desc')
                ->paginate(['list_rows'=>$pageSize,'page'=>$page])
                ->toArray();
            return json(['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1]);
        }

        $khRankList = Db::table('crm_client_rank')->select();
        $khStatusList = Db::table('crm_client_status')->select();
        $xsSourceList = Db::table('crm_source')->select();

        View::assign('khRankList',$khRankList);
        View::assign('khStatusList',$khStatusList);
        View::assign('xsSourceList',$xsSourceList);  //线索/客户来源
         //查询所有管理员（去除admin）
        $adminResult = Db::name('admin')->where('group_id','<>', 1)->field('admin_id,username')->select();
        View::assign('adminResult',$adminResult);
        return View::fetch('client/chengjiao');
    }
    public function myXlsUpload(){
        return $this->xlsUpload();
    }
    //批量导入，客户上传
    public function xlsUpload(){
        @ini_set("memory_limit",'-1');
        @ini_set('max_execution_time', '0');
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('xlsFile');
        try {
            validate(['xlsFile'=>'fileSize:209715200|fileExt:xlsx,xls'])->check(['xlsFile'=>$file]);
            // 上传到本地服务器
            $fileSystem=\think\facade\Filesystem::disk('local');
            $savename = $fileSystem->putFile( 'xls', $file,'md5');
            $info=$fileSystem->path($savename);
        } catch (\think\exception\ValidateException $e) {
            $this->error($e->getMessage());
        }
        if (file_exists($info)) {
            $res = importExecl($info);
            if(!$res['code']){
                $this->error($res['msg']);
            }
            $result=$res['data'];
            $username=$this->admin['username'];
            $map['a.username'] =  $username;
            $max_customers_num=Db::table(config('database.connections.mysql.prefix').'admin')->alias('a')->cache('max_customers_num_'.$username)
                ->join(config('database.connections.mysql.prefix').'auth_group ag','a.group_id = ag.group_id','left')
                ->where($map)
                ->value('ag.max_customers_num');
            unset($result[0]); //移除标题
            if(empty($result)){
                $this->error('导入获取的客户信息为空！');
            }
            if( $max_customers_num > 0){
                //            验证业务员的最大容量
                $ins_c=count($result);
                $cz_c=Db::table('crm_customer')->whereRaw('pr_user=:username AND status=1 AND `issuccess` = -1',['username'=>$username])->count();
                $yx_c=$max_customers_num-$cz_c;
                if($yx_c<$ins_c){
                    if($yx_c<=0){
                        $msg='您当前可最大拥有的客户数量已满，无法导入';
                    }else{
                        $msg='您当前最多可导入客户数量'.$yx_c;
                    }
                    $msg = ['code' => -200,'msg'=>$msg,'data'=>[]];
                    return json($msg);
                }

            }
           /* $count = count($result); //统计总数据
            if ($count>1000){
                $msg = ['code' => -200,'msg'=>'数据量过大，请分批导入！','data'=>[]];
                return json($msg);
            }*/

            $insDate=[];
            //$userExists = []; //已存在的线索
            $leadsModel=\think\facade\Db::name('crm_customer');
            $i=0;
            foreach ($result as $value){
                //看下手机号是否存在。将存在的手机号在数组里删除。
                $userExist = $leadsModel->removeOption()->where('phone', $value['E'])->find();
                if (empty($userExist)){
                    $data=[];
                    $data['name'] = $value['A'];//A客户名称

                    $data['xs_area'] = $value['B'];//B 地区

                    $data['kh_hangye'] = $value['C'];//C 行业类别

                    $data['kh_contact'] = $value['D'];//D 联系人

                    $data['phone'] = $value['E'];//E 联系号码

                    $data['kh_rank'] = $value['F'];//F 客户级别

                    $data['kh_status'] = $value['G'];//G 客户状态

                    $data['email'] = $value['H'];//H邮箱

                    $data['remark'] = $value['I'];//G 备注

                    $data['pr_user'] = $username;//H 负责人
                    $data['ut_time'] =  date("Y-m-d H:i:s",time());//Q更新于
                    $data['at_time'] = date("Y-m-d H:i:s",time());//R创建时间
                    $data['at_user'] = $username;//T创建人
                    $data['status'] = 1;
                    $insDate[]=$data;
                }else{
                    $i++;
                }
            }

        if($insDate){
            $failcount = count($insDate); //最终的总数
            $insertAll = Db::table('crm_customer')->insertAll($insDate);
            if ($insertAll){
                $msg='导入'.$failcount.'条数据成功！';
                if($i){
                    $msg=$msg.'已过滤重复客户信息'.$i.'条!';
                }
                $msg = ['code' => 0,'msg'=>$msg,'data'=>[]];
                return json($msg);
            }else{
                $msg = ['code' => -200,'msg'=>'客户导入失败！','data'=>[]];
                return json($msg);
            }
        }elseif($i){
            $msg = ['code' => -200,'msg'=>'导入客户数据失败！,已过滤重复客户信息'.$i.'条!','data'=>[]];
            return json($msg);
        }

        }else{
            $this->error('上传文件保存失败');
        }

    }

    public function add(){
        if($this->request->isPost()){
            $map['a.admin_id'] =  $this->admin['admin_id'];
            $username=$this->admin['username'];
            $max_customers_num=Db::table(config('database.connections.mysql.prefix').'admin')->alias('a')->cache('max_customers_num_'.$username)
                ->join(config('database.connections.mysql.prefix').'auth_group ag','a.group_id = ag.group_id','left')
                ->where($map)
                ->value('ag.max_customers_num');

            if( $max_customers_num > 0){
                //验证业务员的最大容量
                $cz_c=Db::table('crm_customer')->whereRaw('pr_user=:username AND status=1 AND `issuccess` = -1',['username'=>$username])->count();
                $yx_c=$max_customers_num-$cz_c;
                if($yx_c<=0){
                    $msg='您最大拥有的客户数量已满,如果需要新增请先转移部分客户至公海！';
                    $msg = ['code' => -200,'msg'=>$msg,'data'=>[]];
                    return json($msg);
                }

            }

            $data['phone']       = Request::param('phone');
            $data['wechat']      = Request::param('wechat');
            $data['name']        = Request::param('name');
            $data['xs_area']     = Request::param('xs_area');
            $data['kh_hangye']   = Request::param('kh_hangye');
            $data['kh_contact']  = Request::param('kh_contact');
            $data['kh_rank']     = Request::param('kh_rank');
            $data['kh_status']   = Request::param('kh_status');
            $data['kh_username'] = Request::param('kh_username');
            $data['remark']      = Request::param('remark');

            // $data['kh_need']  = Request::param('kh_need');
            $data['at_user']     = $this->admin['username'];
            $data['pr_user']     = $this->admin['username'];
            $data['pr_user_bef'] = $this->admin['username'];
            $data['ut_time']     = date("Y-m-d H:i:s",time());
            $data['at_time']     = date("Y-m-d H:i:s",time());
            $data['status']      = 1;
            $data['ispublic']    = 3;
            $userExist = \think\facade\Db::name('crm_customer')->where('phone', $data['phone'])->find();
            if ($userExist){
                $msg = ['code' => -200,'msg'=>'抱歉，重复联系号码不可添加！','data'=>[]];
                return json($msg);
            }

            $result = Db::table('crm_customer')->insert($data);
            if ($result){
                $msg = ['code' => 0,'msg'=>'添加成功！','data'=>[]];
                return json($msg);
            }else{
                $msg = ['code' => -200,'msg'=>'添加失败！','data'=>[]];
                return json($msg);
            }
        }


        // $xsSourceList = Db::table('crm_source')->select();
        $khRankList   = Db::table('crm_client_rank')->select();
        $khStatusList = Db::table('crm_client_status')->select();
        $xsAreaList   = Db::table('crm_clues_area')->select();
        $xsHangyeList = Db::table('crm_client_hangye')->select();
        View::assign('xsHangyeList',$xsHangyeList);
        View::assign('xsAreaList',$xsAreaList);
        View::assign('khRankList',$khRankList);
        View::assign('khStatusList',$khStatusList);

        return View::fetch('client/add');
    }
    //编辑客户
    public function edit(){
        if ($this->request->isAjax()){
            $data  = $this->request->post();
            $data['ut_time'] = date("Y-m-d H:i:s",time());

            $result = Db::table('crm_customer')->where(['id'=>$data['id']])->where('status',1)->update($data);
            if ($result){
                $msg = ['code' => 0,'msg'=>'编辑成功！','data'=>[]];
                return json($msg);
            }else{
                $msg = ['code' => -200,'msg'=>'编辑失败！','data'=>[]];
                return json($msg);
            }
        }


        $result = Db::table('crm_customer') ->where(['id' => Request::param('id')])->find();

        View::assign('result',$result);

        // $xsSourceList = Db::table('crm_source')->select();
        $khRankList = Db::table('crm_client_rank')->select();
        $khStatusList = Db::table('crm_client_status')->select();
        $xsAreaList = Db::table('crm_clues_area')->select();
        $xsHangyeList = Db::table('crm_client_hangye')->select();
        View::assign('xsHangyeList',$xsHangyeList);
        View::assign('xsAreaList',$xsAreaList);
        // View::assign('xsSourceList',$xsSourceList);
        View::assign('khRankList',$khRankList);
        View::assign('khStatusList',$khStatusList);

        return View::fetch('client/edit');
    }

    //编辑客户我的
    public function myedit(){
        if ($this->request->isAjax()){
            $data  = $this->request->post();
            $data['ut_time'] = date("Y-m-d H:i:s",time());
            $result = Db::table('crm_customer')->where(['id'=>$data['id']])->where('status',1)->where('pr_user','=',$this->admin['username'])->update($data);
            if ($result){
                $msg = ['code' => 0,'msg'=>'编辑成功！','data'=>[]];
                return json($msg);
            }else{
                $msg = ['code' => -200,'msg'=>'编辑失败！','data'=>[]];
                return json($msg);
            }
        }


        $result = Db::table('crm_customer') ->where(['id' => Request::param('id')])->where('pr_user','=',$this->admin['username'])->find();
        if(empty($result)){
            $msg = ['code' => -200,'msg'=>'编辑信息不存在或不是您的客户信息！','data'=>[]];
            return json($msg);
        }

        View::assign('result',$result);

        // $xsSourceList = Db::table('crm_source')->select();
        $khRankList = Db::table('crm_client_rank')->select();
        $khStatusList = Db::table('crm_client_status')->select();
        $xsAreaList = Db::table('crm_clues_area')->select();
        $xsHangyeList = Db::table('crm_client_hangye')->select();
        View::assign('xsHangyeList',$xsHangyeList);
        View::assign('xsAreaList',$xsAreaList);
        // View::assign('xsSourceList',$xsSourceList);
        View::assign('khRankList',$khRankList);
        View::assign('khStatusList',$khStatusList);

        return View::fetch('client/edit');
    }
    //删除客户
    public function del(){
        $id = Request::param('id');
        if(is_string($id)){
            $where=['id','=',$id];
        }elseif(is_array($id)){
            $where=['id','in',$id];
        }else{
            $msg = ['code' => -200,'msg'=>'请求参数有误！','data'=>[]];
            return json($msg);
        }
        $result = Db::table('crm_customer')->where([$where])->where('status','=',1)->delete();
        if ($result){
            $msg = ['code' => 0,'msg'=>'删除成功！','data'=>[]];
            return json($msg);
        }else{
            $msg = ['code' => -200,'msg'=>'删除失败！','data'=>[]];
            return json($msg);
        }
    }

    //删除我的客户
    public function mydel(){
        $id = Request::param('id');
        if(is_string($id)){
            $where=['id','=',$id];
        }elseif(is_array($id)){
            $where=['id','in',$id];
        }else{
            $msg = ['code' => -200,'msg'=>'请求参数有误！','data'=>[]];
            return json($msg);
        }
        $result = Db::table('crm_customer')->where([$where])->where('status','=',1)->where('pr_user','=',$this->admin['username'])->delete();
        if ($result){
            $msg = ['code' => 0,'msg'=>'删除成功！','data'=>[]];
            return json($msg);
        }else{
            $msg = ['code' => -200,'msg'=>'删除失败！','data'=>[]];
            return json($msg);
        }
    }

    //客户级别
    public function rankList(){
        if($this->request->isPost()){
            $page =input('page',1,'intval');
            $pageSize =input('limit',config('app.pageSize'),'intval');
            $list = \think\facade\Db::name('crm_client_rank')
                ->paginate(['list_rows'=>$pageSize,'page'=>$page])
                ->toArray();
            return json(['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1]);
        }
        return View::fetch();
    }
    //添加客户级别
    public function rankAdd(){
        if($this->request->isPost()){
            $data['rank_name'] = Request::param('rank_name');
            $data['add_time'] = time();
            $result = Db::table('crm_client_rank')->insert($data);
            if ($result){
                $msg = ['code' => 0,'msg'=>'添加成功！','data'=>[]];
                return json($msg);
            }else{
                $msg = ['code' => -200,'msg'=>'添加失败！','data'=>[]];
                return json($msg);
            }
        }
        return View::fetch('client/rank_list_add');
    }
    //编辑客户级别
    public function rankEdit(){
        if ($this->request->isAjax()){
            $data  = $this->request->post();
             // 获取原状态
            $oldstatus = Db::table('crm_client_rank')->where(['id'=>$data['id']])->find();
            $oldstatusname = $oldstatus['rank_name'];
            $ischange = false;
            if ($oldstatusname == $data['rank_name']) {
                $msg = ['code' => -200,'msg'=>'没有变化无需修改','data'=>[]];
                return json($msg);
            }else{
                $ischange = true;
            }

            $result = Db::table('crm_client_rank')->where(['id'=>$data['id']])->update($data);
            if ($result){
                // 状态修改后 客户编辑的原来状态都必须修改
                if ($ischange) {
                    // 所有的客户状态全部膝盖
                    $result2 = Db::table('crm_customer')->where(['kh_rank'=>$oldstatusname])->update(['kh_rank'=>$data['rank_name']]);
                }
                $msg = ['code' => 0,'msg'=>'编辑成功！','data'=>[]];
                return json($msg);
            }else{
                $msg = ['code' => -200,'msg'=>'编辑失败！','data'=>[]];
                return json($msg);
            }
        }

        $result = Db::table('crm_client_rank') ->where(['id' => Request::param('id')])->find();
        View::assign('result',$result);
        return View::fetch('client/rank_list_edit');
    }
    //删除客户级别
    public function rankDel(){
        $id = Request::param('id');
        // 获取原状态
        $oldstatus = Db::table('crm_client_rank')->where(['id'=>$id])->find();
        $oldstatusname = $oldstatus['rank_name'];

        $result = Db::table('crm_client_rank')->where('id',$id)->delete();
        if ($result){
            // 所有的客户状态全部膝盖
            $result2 = Db::table('crm_customer')->where(['kh_rank'=>$oldstatusname])->update(['kh_rank'=>'']);
            $msg = ['code' => 0,'msg'=>'删除成功！','data'=>[]];
            return json($msg);
        }else{
            $msg = ['code' => -200,'msg'=>'删除失败！','data'=>[]];
            return json($msg);
        }
    }


    //客户状态
    public function statusList(){
        if($this->request->isPost()){
            $page =input('page',1,'intval');
            $pageSize =input('limit',config('app.pageSize'),'intval');
            $list = \think\facade\Db::name('crm_client_status')
                ->paginate(['list_rows'=>$pageSize,'page'=>$page])
                ->toArray();
            return json(['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1]);
        }
        return View::fetch();
    }
    //添加客户状态
    public function statusAdd(){
        if($this->request->isPost()){
            $data['status_name'] = Request::param('status_name');
            $data['add_time'] = time();
            $result = Db::table('crm_client_status')->insert($data);
            if ($result){
                $msg = ['code' => 0,'msg'=>'添加成功！','data'=>[]];
                return json($msg);
            }else{
                $msg = ['code' => -200,'msg'=>'添加失败！','data'=>[]];
                return json($msg);
            }
        }
        return View::fetch('client/status_list_add');
    }
    //编辑客户状态
    public function statusEdit(){
        if ($this->request->isAjax()){
            $data  = $this->request->post();
            // 获取原状态
            $oldstatus = Db::table('crm_client_status')->where(['id'=>$data['id']])->find();
            $oldstatusname = $oldstatus['status_name'];
            $newstatusname = $data['status_name'];
            $ischange = false;
            if ($oldstatusname == $newstatusname) {
                $msg = ['code' => -200,'msg'=>'状态没有变化无需修改','data'=>[]];
                return json($msg);
            }else{
                $ischange = true;
            }
            $result = Db::table('crm_client_status')->where(['id'=>$data['id']])->update($data);
            if ($result){
                // 状态修改后 客户编辑的原来状态都必须修改
                if ($ischange) {
                    // 所有的客户状态全部膝盖
                    $result2 = Db::table('crm_customer')->where(['kh_status'=>$oldstatusname])->update(['kh_status'=>$newstatusname]);
                }
                $msg = ['code' => 0,'msg'=>'编辑成功！','data'=>[]];
                return json($msg);
            }else{
                $msg = ['code' => -200,'msg'=>'编辑失败！','data'=>[]];
                return json($msg);
            }
        }


        $result = Db::table('crm_client_status') ->where(['id' => Request::param('id')])->find();
        View::assign('result',$result);
        return View::fetch('client/status_list_edit');
    }
    //删除客户状态
    public function statusDel(){
        $id = Request::param('id');
        // 获取原状态
        $oldstatus = Db::table('crm_client_status')->where(['id'=>$id])->find();
        $oldstatusname = $oldstatus['status_name'];
        // $ischange = false;
        // if ($oldstatusname == $data['status_name']) {
        //     $msg = ['code' => -200,'msg'=>'状态没有变化无需修改','data'=>[]];
        //     return json($msg);
        // }else{
        //     $ischange = true;
        // }
        $result = Db::table('crm_client_status')->where('id',$id)->delete();
        if ($result){
            // 所有的客户状态全部置空
            Db::table('crm_customer')->where(['kh_status'=>$oldstatusname])->update(['kh_status'=>'']);
            $msg = ['code' => 0,'msg'=>'删除成功！','data'=>[]];
            return json($msg);
        }else{
            $msg = ['code' => -200,'msg'=>'删除失败！','data'=>[]];
            return json($msg);
        }
    }


    //移入公海
    public function toMoveGh(){
         //1，获取提交的线索ID 【1,2,3,4,】
        $ids = Request::param('ids');
        View::assign('ids',$ids);
        if ($this->request->isAjax()){
            $pr_gh_type = Request::param('pr_gh_type');
            $idsArr = explode(",",$ids);


            $count = 0;
            foreach ($idsArr as $value){
                $data['pr_user_bef'] = Db::table('crm_customer')->where(['id'=>$value])->value('pr_user');
                if(empty($data['pr_user_bef'])){
                    $data['pr_user_bef']='';
                }
                $data['pr_user'] = '';
                // $data['pr_user_bef'] = Db::table('crm_customer')->where(['id'=>$value])->field('pr_user')->find();
                // $data['pr_user'] = $username;
                // $data['id'] = $value;
                // $insertAll = Db::name('crm_customer')->update($data);
                $data['pr_gh_type'] = $pr_gh_type;
                $data['to_gh_time'] = date("Y-m-d H:i:s",time());
                $data['status'] = 2;//0-线索，1客户，2公海
                $data['id']  = $value;
                $result = Db::table('crm_customer')->where(['id'=>$value])->update($data);
                if ($result){
                    $count ++;
                }
            }
            if ($count > 0){
                $msg = ['code' => 0,'msg'=>$count.'个客户移入公海成功！','data'=>[]];
                return json($msg);
            }else{
                $msg = ['code' => -200,'msg'=>'转入公海失败！','data'=>[]];
                return json($msg);
            }
            // $data['pr_gh_type'] = Request::param('pr_gh_type');
            // $data['to_gh_time'] = date("Y-m-d H:i:s",time());
            // $data['status'] = 2;//0-线索，1客户，2公海
            // $data['id']  = Request::param('id');
            // $result = Db::table('crm_customer')->where(['id'=>$data['id']])->update($data);
            // if ($result){
            //     $msg = ['code' => 0,'msg'=>'移入公海成功！','data'=>[]];
            //     return json($msg);
            // }else{
            //     $msg = ['code' => -200,'msg'=>'抱歉，移入公海失败！','data'=>[]];
            //     return json($msg);
            // }
        }


        $libTypeList = Db::table('crm_liberum_type')->select();

        View::assign('libTypeList',$libTypeList);

        // $result = Db::table('crm_customer') ->where(['id' => Request::param('id')])->find();
        // View::assign('result',$result);
        return View::fetch('client/move_gh');
    }
    //客户搜索
    public function clientSearch(){
        $page =input('page',1,'intval');
        $limit =input('limit')?input('limit'):config('app.pageSize');
        $keyword = Request::param('keyword');
        $list=  $this->model -> getClientSearchList($page,$limit,$keyword);
        return json(['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1]);

    }
    //（我的客户）搜索
    public function personClientSearch(){
        $page =input('page',1,'intval');
        $limit =input('limit')?input('limit'):config('app.pageSize');
        $keyword = Request::param('keyword');
        $list=  $this->model -> getPersonClientSearchList($page,$limit,$keyword,$this->admin);
        return json(['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1]);

    }
    //（我的客户）搜索
    public function chengjiaoClientSearch(){
        $page =input('page',1,'intval');
        $limit =input('limit')?input('limit'):config('app.pageSize');
        $keyword = $this->request->post('keyword');
        $list=  $this->model -> getChengjiaoClientSearchList($page,$limit,$keyword,$this->admin);
        return json(['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1]);

    }
    //写跟进
    public function dialogue(){
        $result = Db::table('crm_customer')->where(['id'=>Request::param('id')])->find();

        $result['comment']= Db::table('crm_comment')->alias('com')->join('admin adm','com.user_id = adm.admin_id')->where(['customer_id'=>Request::param('id')])->field('com.*,adm.username,adm.avatar')->select()->toArray();
        foreach ($result['comment'] as $k => $v){
            $result['comment'][$k]['reply'] = Db::table('crm_reply')->where(['comment_id'=>$v['id']])->select();
        }
         // 是否有查看手机号的权限
        $userinfo = Db::name('admin')->where('username',$this->admin['username'])->find();
        if ($userinfo['isphone'] == 0) {
            $result['phone'] = mb_substr($result['phone'], 0, 3).'****'. mb_substr($result['phone'], 7, 11);
        }
        View::assign('result',$result);
        return View::fetch('client/dialogue');
    }

    //评论
    public function comment(){
        if($this->request->post()){
            $data['customer_id'] = Request::param('customer_id');
            if(empty($data['customer_id'])){
                return json(['code'=>1,'msg'=>'请求参数非法!']);
            }
            $data['user_id'] = $this->admin['admin_id'];
            $data['reply_msg'] = Request::param('reply_msg');
            $data['create_date'] = time();

            //更新跟进记录
            $genjin['last_up_records'] = $data['reply_msg'];
            $genjin['last_up_time'] = date("Y-m-d H:i:s",$data['create_date']);
            $next_time = Request::param('next_up_time');
            $genjin['next_up_time'] = $next_time?$next_time:date("Y-m-d",strtotime("+1 day"));
            Db::table('crm_customer')->where(['id'=>$data['customer_id']])->update($genjin);

            $result = Db::table('crm_comment')->insert($data);
            $data['create_date'] = date("Y年m月d日 H:i",$data['create_date']);

            if ($result){
                return json(['code'=> 0,'msg'=>'跟进记录成功！','data'=>$data]);
            }else{
                return json(['code'=>1,'msg'=>'跟进记录失败!']);
            }
        }

    }

    //回复
    public function reply(){
        $data['comment_id'] = Request::param('cid');
//        $data['from_user_id'] = Session::get('user.id');
        $data['from_user_id'] = $this->admin['admin_id'];
        $data['to_user_id'] = Request::param('to_uid');
        $data['reply_msg'] = Request::param('reply_msg');
        $data['create_date'] = time();
        $result = Db::table('crm_reply')->insert($data);
        $data['create_date'] = date("Y年m月d日 H:i",$data['create_date']);
        if ($result){
            return json(['code'=> 0,'msg'=>'回复成功！','data'=>$data]);
        }else{

            return json(['code'=>1,'msg'=>'回复失败！']);

        }
    }


    //客户转移，变更负责人
    public function alterPrUser(){
        //1，获取提交的线索ID 【1,2,3,4,】
        $ids = Request::param('ids');
        View::assign('ids',$ids);


        //查询所有管理员（去除admin）
        $adminResult = Db::name('admin')->where('group_id','<>', 1)->field('admin_id,username')->select();
        View::assign('adminResult',$adminResult);

        if ($this->request->isAjax()){
            $username = Request::param('username');
            $idsArr = explode(",",$ids);


            $count = 0;
            foreach ($idsArr as $key => $value){
                $data['pr_user_bef'] = Db::table('crm_customer')->where(['id'=>$value])->value('pr_user');
                $data['pr_user'] = $username;
                $data['id'] = $value;
                $insertAll = Db::name('crm_customer')->update($data);
                if ($insertAll){
                    $count ++;
                }
            }




            if ($count > 0){
                $msg = ['code' => 0,'msg'=>'转移'.$count.'个客户成功！','data'=>[]];
                return json($msg);
            }else{
                $msg = ['code' => -200,'msg'=>'转移失败！','data'=>[]];
                return json($msg);
            }
        }

        return View::fetch('client/alter_pr_user');
    }


    //客户转移，变更负责人(个人)
    public function alterPrUserPri(){
        //1，获取提交的线索ID 【1,2,3,4,】
        $ids = Request::param('ids');
        View::assign('ids',$ids);

        if ($this->request->isAjax()){
            $username = Request::param('username');
            $idsArr = explode(",",$ids);
            $count = 0;
            if(empty($username)){
                $msg = ['code' => -200,'msg'=>'请求参数非法！','data'=>[]];
                return json($msg);
            }
            $map['a.username'] =  $username;
            $max_customers_num=Db::table(config('database.connections.mysql.prefix').'admin')->alias('a')->cache('max_customers_num_'.$username)
                ->join(config('database.connections.mysql.prefix').'auth_group ag','a.group_id = ag.group_id','left')
                ->where($map)
                ->value('ag.max_customers_num');
            if( $max_customers_num > 0){
                //            验证业务员的最大容量
                $ins_c=count($idsArr);
                $cz_c=Db::table('crm_customer')->whereRaw('pr_user=:username AND status=1 AND `issuccess` = -1',['username'=>$username])->count();
                $yx_c=$max_customers_num-$cz_c;
                if($yx_c<$ins_c){
                    if($yx_c<=0){
                        $msg=$username.'可最大拥有的客户数量已满';
                    }else{
                        $msg=$username.'最多可转入客户数量'.$yx_c;
                    }
                    $msg = ['code' => -200,'msg'=>$msg,'data'=>[]];
                    return json($msg);
                }

            }
            foreach ($idsArr as $key => $value){
                $data['pr_user_bef'] = Db::table('crm_customer')->where(['id'=>$value])->value('pr_user');
                $data['pr_user'] = $username;
                $data['id'] = $value;
                $insertAll = Db::name('crm_customer')->update($data);
                if ($insertAll){
                    $count ++;
                }
            }
            if ($count > 0){
                $msg = ['code' => 0,'msg'=>'转移'.$count.'个客户成功！','data'=>[]];
                return json($msg);
            }else{
                $msg = ['code' => -200,'msg'=>'转移失败！','data'=>[]];
                return json($msg);
            }
        }
        //查询所有管理员（去除admin）
        $adminResult = Db::name('admin')->where('group_id','<>', 1)->field('admin_id,username')->select();
        View::assign('adminResult',$adminResult);
        return View::fetch('personclient/alter_pr_user');
    }

     //客户行业
    public function hangyeList(){
        if($this->request->isPost()){
            $page =input('page',1,'intval');
            $pageSize =input('limit',config('app.pageSize'),'intval');
            $list = \think\facade\Db::name('crm_client_hangye')
                ->paginate(['list_rows'=>$pageSize,'page'=>$page])
                ->toArray();
            return json(['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1]);
        }
        return View::fetch();
    }
    //添加客户级别
    public function hangyeAdd(){
        if($this->request->isPost()){
            $data['hy_name'] = Request::param('hy_name');
            $data['add_time'] = time();
            $result = Db::table('crm_client_hangye')->insert($data);
            if ($result){
                $msg = ['code' => 0,'msg'=>'添加成功！','data'=>[]];
                return json($msg);
            }else{
                $msg = ['code' => -200,'msg'=>'添加失败！','data'=>[]];
                return json($msg);
            }
        }
        return View::fetch('client/hangye_list_add');
    }
    //编辑客户级别
    public function hangyeEdit(){
        if ($this->request->isAjax()){
            $data  = $this->request->post();
             // 获取原状态
            $oldstatus = Db::table('crm_client_hangye')->where(['id'=>$data['id']])->find();
            $oldstatusname = $oldstatus['hy_name'];
            $ischange = false;
            if ($oldstatusname == $data['hy_name']) {
                $msg = ['code' => -200,'msg'=>'没有变化无需修改','data'=>[]];
                return json($msg);
            }else{
                $ischange = true;
            }

            $result = Db::table('crm_client_hangye')->where(['id'=>$data['id']])->update($data);
            if ($result){
                // 状态修改后 客户编辑的原来状态都必须修改
                if ($ischange) {
                    // 所有的客户状态全部膝盖
                    $result2 = Db::table('crm_customer')->where(['kh_hangye'=>$oldstatusname])->update(['kh_hangye'=>$data['hy_name']]);
                }
                $msg = ['code' => 0,'msg'=>'编辑成功！','data'=>[]];
                return json($msg);
            }else{
                $msg = ['code' => -200,'msg'=>'编辑失败！','data'=>[]];
                return json($msg);
            }
        }

        $result = Db::table('crm_client_hangye') ->where(['id' => Request::param('id')])->find();
        View::assign('result',$result);
        return View::fetch('client/hangye_list_edit');
    }
    //删除客户级别
    public function hangyeDel(){
        $id = Request::param('id');
        // 获取原状态
        $oldstatus = Db::table('crm_client_hangye')->where(['id'=>$id])->find();
        $oldstatusname = $oldstatus['hy_name'];

        $result = Db::table('crm_client_hangye')->where('id',$id)->delete();
        if ($result){
            // 所有的客户状态全部膝盖
            $result2 = Db::table('crm_customer')->where(['kh_hangye'=>$oldstatusname])->update(['kh_hangye'=>'']);
            $msg = ['code' => 0,'msg'=>'删除成功！','data'=>[]];
            return json($msg);
        }else{
            $msg = ['code' => -200,'msg'=>'删除失败！','data'=>[]];
            return json($msg);
        }
    }

}
